import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';
import router from '@/router';

// 创建用户 store 实例
let userStore;

// 延迟初始化用户 store，避免在模块加载时初始化
const getUserStore = () => {
    if (!userStore) {
        userStore = useUserStore();
    }
    return userStore;
};

// 统一的错误处理函数
const handleApiError = (error, operation) => {
    console.error(`${operation}失败:`, error);

    // 检查是否是 token 过期错误
    if (error.response && error.response.data) {
        const errorMsg = error.response.data.msg || error.response.data.message;
        if (errorMsg && (errorMsg.includes('登录已过期') ||
            errorMsg.includes('无效的token') ||
            errorMsg.includes('认证失败') ||
            errorMsg.includes('jwt expired'))) {

            ElMessage.error('登录已过期，请重新登录');

            // 清除用户信息
            const store = getUserStore();
            if (store.logout) {
                store.logout();
            }

            // 跳转到登录页面
            if (router && router.push) {
                router.push('/login');
            }

            // 抛出特定的错误，让调用方知道是 token 过期
            const tokenError = new Error('TOKEN_EXPIRED');
            tokenError.originalError = error;
            throw tokenError;
        }
    }

    // 重新抛出原始错误
    throw error;
};

export const goodApi = {
    // 创建二手商品
    async create(data) {
        try {
            console.log('创建商品请求数据:', data);
            const response = await request.post('/api/goods', data);
            return response;
        } catch (error) {
            return handleApiError(error, '创建商品');
        }
    },

    // 获取二手商品列表
    async list(params) {
        try {
            const response = await request.get('/api/goods', { params });
            return response;
        } catch (error) {
            return handleApiError(error, '获取商品列表');
        }
    },

    // 获取简单列表（不关联用户信息）
    async listSimple(params) {
        try {
            const response = await request.get('/api/goods-simple', { params });
            return response;
        } catch (error) {
            return handleApiError(error, '获取简单商品列表');
        }
    },

    // 获取我的商品
    async myGoods(params) {
        try {
            const response = await request.get('/api/goods/my', { params });
            return response;
        } catch (error) {
            return handleApiError(error, '获取我的商品');
        }
    },

    // 获取商品详情
    async detail(id) {
        try {
            const response = await request.get(`/api/goods/${id}`);
            return response;
        } catch (error) {
            return handleApiError(error, '获取商品详情');
        }
    },

    // 更新商品信息
    async update(id, data) {
        try {
            console.log('更新商品请求数据:', data);
            const response = await request.put(`/api/goods/${id}`, data);
            return response;
        } catch (error) {
            return handleApiError(error, '更新商品');
        }
    },

    // 删除商品
    async delete(id) {
        try {
            const response = await request.delete(`/api/goods/${id}`);
            return response;
        } catch (error) {
            return handleApiError(error, '删除商品');
        }
    },

    // 更新商品状态
    async updateStatus(id, status) {
        try {
            const response = await request.patch(`/api/goods/${id}/status`, { status });
            return response;
        } catch (error) {
            return handleApiError(error, '更新商品状态');
        }
    },

    myGoods: (params) => {
        return request({
            url: '/api/good/my',
            method: 'get',
            params
        });
    },
};